import { useAuth } from "../context/auth-context";
import { Button, Form, Input, Card } from "antd";
import { LongButton } from "./index";
import { useAsync } from "utils/use-async";

export const LoginScreen = ({
  onError,
}: {
  onError: (error: Error) => void;
}) => {
  const { login } = useAuth();
  const { run, isLoading } = useAsync();
  // ts是鸭子类型，这是面向接口的类型，并不是面向对象的编程，即使没有引入对应的接口 类型
  // 只要对应的里面的具体的内容是一样的还是会认为是符合对应类型的
  // 比如定义一个接口interface A {id:String},如果const a = {id='1111'}
  // 这个a其实也是符合接口A类型的，在函数传参的时候也是不会报错的
  const handleSubmit = (values: { username: string; password: string }) => {
    run(login(values)).catch((error) => {
      onError(error);
    });
  };

  return (
    <Card style={{ display: "flex", justifyContent: "center" }}>
      <Form onFinish={handleSubmit}>
        <Form.Item
          name={"username"}
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input placeholder={"用户名"} type="text" id={"username"} />
        </Form.Item>
        <Form.Item
          name={"password"}
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input placeholder={"密码"} type="password" id={"password"} />
        </Form.Item>
        <Form.Item>
          <LongButton loading={isLoading} htmlType={"submit"} type={"primary"}>
            登录
          </LongButton>
        </Form.Item>
      </Form>
    </Card>
  );
};
